package com.llkj.qingnianguoxue.music;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.CourseEvaluateAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CommentResponseBean;
import com.llkj.qingnianguoxue.bean.CourseEvaluateBean;
import com.llkj.qingnianguoxue.bean.MusicDetailBean;
import com.llkj.qingnianguoxue.bean.RxMusicLikeBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.MyShare;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MusicDetailActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener,View.OnClickListener,MyShare.ShareResultCallback{
    @BindView(R.id.refresh_layout)
    protected SwipeRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    protected RecyclerView lvEvaluateView;//评价
    private CourseEvaluateAdapter mEvaluateAdapter;
    private List<CourseEvaluateBean> mEvaluateData;
    private int totalSize,mPage;

    protected ImageView ivMusicCorver;//封面
    protected TextView tvSingCount;//人数
    private ImageView ivSaveMusic,ivPraiseMusic,ivLikeMusic;//收藏，点赞，喜欢
    private TextView tvPraiseNum;//点赞数
    private TextView tvMusicTitle;//音乐名称
    private ImageView ivHead;//头像
    private TextView tvName;//名字
    private TextView tvHotAppraise;//评价数量
    private ImageView ivAppraiseBtn;//评价按钮
    private ImageView ivStartSing;//开始伴奏
    private String mMusicId;//曲目id
    private String mMusicCorverUrl;//伴奏音乐封面图片
    private String mMusicName;//伴奏音乐名称
    private String mCountSing;//演唱人数
    private String mMusicBgPath;//背景图片
    private String mMusicUrl;//伴奏音乐
    private String mOriginalMusicUrl;//原唱音乐
    private String mMusicLrcUrl;//歌词url
    private String mArtistName;//作者名
    private int mClickType;//1收藏，2喜欢，3点赞

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_detail);
        ButterKnife.bind(this);
        setTitle("伴奏详情", true, TITLE_TYPE_IMG, R.drawable.icon_back, true,TITLE_TYPE_IMG, R.drawable.icon_book_share);
        Intent intent = getIntent();
        mMusicId = intent.getStringExtra("musicId");
        EventBus.getDefault().register(this);

        initView();
        initListener();

        loadWaitDialog();
        onRefresh();
    }

    private void initView(){
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvEvaluateView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false));
        mEvaluateData = new ArrayList<>();
        mEvaluateAdapter = new CourseEvaluateAdapter(R.layout.item_course_evaluate,mEvaluateData);
        lvEvaluateView.setAdapter(mEvaluateAdapter);

        View headView = LayoutInflater.from(this).inflate(R.layout.header_music_detail,null);
        mEvaluateAdapter.addHeaderView(headView);

        ivMusicCorver = (ImageView) headView.findViewById(R.id.ivMusicCover);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivMusicCorver.getLayoutParams();
        params.height = DisplayUtil.getDensityWdith(this)*9/16;

        tvSingCount = (TextView) headView.findViewById(R.id.tvSingCount);//收藏，点赞，喜欢
        tvPraiseNum = (TextView) headView.findViewById(R.id.tv_praise_num);//点赞数
        ivSaveMusic = (ImageView) headView.findViewById(R.id.ivSaveMusic);
        ivPraiseMusic = (ImageView) headView.findViewById(R.id.ivSavePraise);
        ivLikeMusic = (ImageView) headView.findViewById(R.id.ivLikeMusic);
        tvMusicTitle = (TextView) headView.findViewById(R.id.tvMusicName);
        ivHead  = (ImageView) headView.findViewById(R.id.ivHead);
        tvName  = (TextView) headView.findViewById(R.id.tvName);
        tvHotAppraise = (TextView) headView.findViewById(R.id.tvHotAppraise);
        tvHotAppraise.setText(String.format(getString(R.string.music_detail_elvaluate), String.valueOf(100)));
        ivAppraiseBtn = (ImageView) headView.findViewById(R.id.ivRecomment);
        ivStartSing = (ImageView) headView.findViewById(R.id.ivStartSing);
    }

    @Override
    protected void rightDoWhat() {
        super.rightDoWhat();
        String sharelink = String.format(HttpMethod.SHARE_KOJI,mMusicId);
        DialogUtil.showShareMusicDialog(this,"起范儿音乐",mMusicName,mMusicCorverUrl,sharelink,this);
    }

    @Override
    public void onClick(View view){
        Bundle bundle = null;
        String type = null;
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            dialogConfirm(null, null, null, null).show();
            return;
        }
        switch (view.getId()){
            case R.id.ivStartSing://录制界面
                RecordMusicActivity.startActivity(this,mMusicId,mMusicCorverUrl,mMusicName,mCountSing,mMusicUrl,mOriginalMusicUrl,mMusicLrcUrl,mArtistName);
                break;
            case R.id.ivSaveMusic://保存
                mClickType= 1;
//                loadWaitDialog();
                type = ivSaveMusic.isSelected()?"2":"1";
                HttpMethod.kojiUserOperation(this,this,mMusicId,type,"1");
                break;
            case R.id.ivSavePraise://点赞
                mClickType= 3;
                //loadWaitDialog();
                type = ivPraiseMusic.isSelected()?"2":"1";
                HttpMethod.kojiUserOperation(this,this,mMusicId,type,"3");
                break;
            case R.id.ivLikeMusic://喜欢
                mClickType= 2;
//                loadWaitDialog();
                type = ivLikeMusic.isSelected()?"2":"1";
                HttpMethod.kojiUserOperation(this,this,mMusicId,type,"2");
                break;
            case R.id.ivRecomment://评论
                PublicCommentActivity.startActivity(this,mMusicId);
                break;
        }
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivity(LoginActivity.class);
    }

    @Override
    public void shareResultCallBack(int result) {
        if(result==4){
            boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
            if (!isLogin) {
                dialogConfirm(null, null, null, null).show();
                return;
            }
            DialogUtil.shareCircle(this,mMusicId,mMusicName,mCountSing,mMusicCorverUrl,null);
        }
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getData();
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getData();
    }

    private void getData(){
        HttpMethod.kojiDetails(this,this,String.valueOf(mPage),mMusicId);
    }

    private void initListener(){
        ivStartSing.setOnClickListener(this);
        ivSaveMusic.setOnClickListener(this);
        ivPraiseMusic.setOnClickListener(this);
        ivLikeMusic.setOnClickListener(this);
        ivAppraiseBtn.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);
        mEvaluateAdapter.setOnLoadMoreListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentPublic(CommentResponseBean responseBean){
        if(responseBean.publishSuccess){
            onRefresh();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        refreshLayout.setRefreshing(false);
        if (HttpMethod.HTTP_KOJI_DETAILS == method) {
            MusicDetailBean detailBean = GsonUtil.GsonToBean(data,MusicDetailBean.class);
            if(detailBean!=null) {
                totalSize = Integer.parseInt(detailBean.getNum());
                if (mPage == 1) {
                    if(detailBean.getDetails()!=null){
                        mMusicCorverUrl = detailBean.getDetails().getSing_img();//伴奏音乐封面图片
                        mMusicName = detailBean.getDetails().getName();//伴奏音乐名称
                        mCountSing = detailBean.getDetails().getPlay_num();//演唱人数
                        mMusicUrl = detailBean.getDetails().getAccompaniment();//伴奏音乐
                        mOriginalMusicUrl = detailBean.getDetails().getMp3();//原唱音乐
                        mArtistName = detailBean.getDetails().getSing_name();
                        mMusicLrcUrl = detailBean.getDetails().getLyric();//歌词url
                        ImageLoadingUtil.loadingUrl(ivMusicCorver,detailBean.getDetails().getBg_img());
                        ImageLoadingUtil.loadingCircleBorderImg(ivHead,mMusicCorverUrl, R.color.transparent);
                        tvMusicTitle.setText(mMusicName);
                        tvName.setText(mArtistName);
                        tvSingCount.setText(mCountSing +"人播放");
                        tvHotAppraise.setText(String.format(getString(R.string.music_detail_elvaluate),detailBean.getNum()));
//                        ivSaveMusic,ivPraiseMusic,;//收藏，点赞
                        if("1".equals(detailBean.getDetails().getIs_like())){//喜欢
                            ivLikeMusic.setSelected(true);
                        }else{
                            ivLikeMusic.setSelected(false);
                        }

                        tvPraiseNum.setText(detailBean.getDetails().getFans());
                        if("1".equals(detailBean.getDetails().getIs_fans())){//点赞
                            ivPraiseMusic.setSelected(true);
                        }else{
                            ivPraiseMusic.setSelected(false);
                        }

                        if("1".equals(detailBean.getDetails().getIs_collection())){//收藏
                            ivSaveMusic.setSelected(true);
                        }else{
                            ivSaveMusic.setSelected(false);
                        }
                    }

                    mEvaluateData.clear();
                    LoadDataHelper.refreshComplete(mEvaluateAdapter, mEvaluateData, refreshLayout, lvEvaluateView);
                } else {
                    mEvaluateAdapter.setEnableLoadMore(true);
                    mEvaluateAdapter.loadMoreComplete();
                }
                mEvaluateData.addAll(detailBean.getComment());
                mEvaluateAdapter.notifyDataSetChanged();
            }
        }else if(HttpMethod.HTTP_KOJI_USER_OPERATION == method){
            if(mClickType==1){
                ivSaveMusic.setSelected(!ivSaveMusic.isSelected());
            }else  if(mClickType==2){
                ivLikeMusic.setSelected(!ivLikeMusic.isSelected());
                RxBus.getInstance().post(new RxMusicLikeBean(ivLikeMusic.isSelected()));
            }else  if(mClickType==3){
                ivPraiseMusic.setSelected(!ivPraiseMusic.isSelected());
                try {
                    int praiseNum = Integer.parseInt(tvPraiseNum.getText().toString());
                    praiseNum = ivPraiseMusic.isSelected()?++praiseNum:--praiseNum;
                    tvPraiseNum.setText(String.valueOf(praiseNum));
                }catch (Exception e){}
            }
        }
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, mEvaluateAdapter, null, lvEvaluateView, totalSize);
    }
}
